﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.IO;

namespace zqdn.Web.Controllers
{
    public class WxController : Controller
    {

        /// <summary>
        /// 服务号授权
        /// <summary>
        /// 对页面是否要用授权 用snsapi_base方式 获取Code Appid是微信应用id
        /// </summary>
        /// <returns></returns>
        JavaScriptSerializer Jss = new JavaScriptSerializer();

        //string host = "http://zqdn-dev.rndcn.com";
        string host = "http://zqdn.aegis-s.com";

        //吾测测微信配置
        //string Appid = "wxa3fe386216434a6b";
        //string Appsecret = "489858ba90a6b1bb6f2895ae0eb256a2";

        //最强大脑微信配置
        string Appid = "wx27a54ca734af2cf8";
        string Appsecret = "51501b489632695f29c7f2577c0ab9fe";

        public string GetCodeUrl(string Appid, string redirect_uri)
        {
            return string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect", Appid, redirect_uri);
        }


        public ActionResult GetWxUser(string code)
        {
            string _code = code;
            //WriteLog(code);
            string openid = CodeGetOpenid(Appid, Appsecret, _code);
            //WriteLog(openid);
            Dictionary<string, object> info = GetUserInfo(openid);
            return Redirect("" + host + "/h5/#/regist?openid=" + openid + "&nickname=" + info["nickname"].ToString() + "&headimgurl=" + info["headimgurl"].ToString() + "");
            //return GetUserInfo(openid);
        }

        public ActionResult GetWxUserToCase(string code)
        {
            string _code = code;
            //WriteLog(code);
            string openid = CodeGetOpenid(Appid, Appsecret, _code);
            //WriteLog(openid);
            Dictionary<string, object> info = GetUserInfo(openid);
            return Redirect("" + host + "/h5/#/caseselect?openid=" + openid + "&nickname=" + info["nickname"].ToString() + "&headimgurl=" + info["headimgurl"].ToString() + "");
            //return GetUserInfo(openid);
        }

        public ActionResult GetWxUserToEx(string code)
        {
            string _code = code;
            //WriteLog(code);
            string openid = CodeGetOpenid(Appid, Appsecret, _code);
            //WriteLog(openid);
            Dictionary<string, object> info = GetUserInfo(openid);
            return Redirect("" + host + "/h5/#/ex?openid=" + openid + "&nickname=" + info["nickname"].ToString() + "&headimgurl=" + info["headimgurl"].ToString() + "");
            //return GetUserInfo(openid);
        }

        public ActionResult GetWxUserToInfo(string code)
        {
            string _code = code;
            //WriteLog(code);
            string openid = CodeGetOpenid(Appid, Appsecret, _code);
            //WriteLog(openid);
            Dictionary<string, object> info = GetUserInfo(openid);
            return Redirect("" + host + "/h5/#/user/info?openid=" + openid + "&nickname=" + info["nickname"].ToString() + "&headimgurl=" + info["headimgurl"].ToString() + "");
            //return GetUserInfo(openid);
        }

        public ActionResult GetWxUserToChange(string code)
        {
            string _code = code;
            //WriteLog(code);
            string openid = CodeGetOpenid(Appid, Appsecret, _code);
            //WriteLog(openid);
            Dictionary<string, object> info = GetUserInfo(openid);
            return Redirect("" + host + "/h5/#/ex/change?openid=" + openid + "&nickname=" + info["nickname"].ToString() + "&headimgurl=" + info["headimgurl"].ToString() + "");
            //return GetUserInfo(openid);
        }

        /// <summary>
        /// 用Code换取Openid
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        public string CodeGetOpenid(string Appid, string Appsecret, string Code)
        {
            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", Appid, Appsecret, Code);
            string ReText = WebRequestPostOrGet(url, "");//post/get方法获取信息 
            Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(ReText);
            if (!DicText.ContainsKey("openid"))
                return "";
            return DicText["openid"].ToString();
        }


        /// <summary>
        /// 用openid换取用户信息
        /// </summary>
        /// <param name="openid">微信标识id</param>
        /// <returns></returns>
        public Dictionary<string, object> GetUserInfo(string openid)
        {
            JavaScriptSerializer Jss = new JavaScriptSerializer();
            string access_token = GetAccessToken(Appid, Appsecret);//ApiCommon.getTokenSession(Appid,appsecret);//获取access_token
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", access_token, openid);
            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(WebRequestPostOrGet(url, ""));
            return respDic;
        }

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns>AccessToken</returns>
        public string GetAccessToken(string appid, string appsecret)
        {
            string accessToken = "";
            string respText = "";
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (Stream resStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream, Encoding.Default);
                respText = reader.ReadToEnd();
                resStream.Close();
            }
            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
            accessToken = respDic["access_token"].ToString();
            return accessToken;
        }


        
        public string GetOpenID(string appid, string secret, string js_code,string grant_type)
        {
            try
            {
                string url = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type={3}", appid, secret, js_code,grant_type);
                //string ReText = WebRequestPostOrGet(url, "");//post/get方法获取信息 
                //Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(ReText);
                ////if (!DicText.ContainsKey("openid"))
                ////    return "";
                ////return DicText["openid"].ToString();
                //return ReText
                var request = (HttpWebRequest)WebRequest.Create(url);
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                return responseString;
            } catch(Exception ex) {
                return ex.ToString();
            }
        }


        #region Post/Get提交调用抓取
        /// <summary>
        /// Post/get 提交调用抓取
        /// </summary>
        /// <param name="url">提交地址</param>
        /// <param name="param">参数</param>
        /// <returns>string</returns>
        public static string WebRequestPostOrGet(string sUrl, string sParam)
        {
            byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam);


            Uri uriurl = new Uri(sUrl);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param);
            req.Method = "Post";
            req.Timeout = 120 * 1000;
            req.ContentType = "application/x-www-form-urlencoded;";
            req.ContentLength = bt.Length;


            using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存
            {
                reqStream.Write(bt, 0, bt.Length);
                reqStream.Flush();
            }
            try
            {
                using (WebResponse res = req.GetResponse())
                {
                    //在这里对接收到的页面内容进行处理 


                    Stream resStream = res.GetResponseStream();


                    StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8);


                    string resLine;


                    System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder();


                    while ((resLine = resStreamReader.ReadLine()) != null)
                    {
                        resStringBuilder.Append(resLine + System.Environment.NewLine);
                    }


                    resStream.Close();
                    resStreamReader.Close();


                    return resStringBuilder.ToString();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;//url错误时候回报错
            }
        }
        #endregion

        public static void WriteLog(string strLog)
        {
            string sFilePath = "d:\\" + DateTime.Now.ToString("yyyyMM");
            string sFileName = "rizhi" + DateTime.Now.ToString("dd") + ".log";
            sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径
            if (!Directory.Exists(sFilePath))//验证路径是否存在
            {
                Directory.CreateDirectory(sFilePath);
                //不存在则创建
            }
            FileStream fs;
            StreamWriter sw;
            if (System.IO.File.Exists(sFileName))
            //验证文件是否存在，有则追加，无则创建
            {
                fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
            }
            else
            {
                fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
            }
            sw = new StreamWriter(fs);
            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "   ---   " + strLog);
            sw.Close();
            fs.Close();
        }


        public string GetOpenID(string Appid, string Appsecret, string Code)
        {
            string url = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&code={2}&grant_type=authorization_code", Appid, Appsecret, Code);
            string ReText = WebRequestPostOrGet(url, "");//post/get方法获取信息 
            Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(ReText);
            if (!DicText.ContainsKey("openid"))
                return "";
            return DicText["openid"].ToString();
        }
    }
}